<?php

namespace App\Http\Controllers;

use function foo\func;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\ImageManager;

class UploadController extends Controller
{
    public function image(Request $request)
    {
        $file = $request->image;
        $from = $request->from;
        $ext  = $file->extension();

        // 检查文件是否有效
        if (!$file->isValid()) {
            return [
                "success" => false,
                "msg"     => "无效的文件",
            ];
        }

        // 校验格式
        if (!in_array($ext, ['png', 'jpg', 'gif', 'jpeg'])) {
            return [
                "success" => false,
                "msg"     => "格式不正确",
            ];
        }

        $path = $file->store($from, 'public');

        // 裁剪图片
        $manager = new ImageManager();
        $image   = $manager->make('storage/' . $path)->resize(150, null, function ($constraint) {
            $constraint->aspectRatio();
        });

        $image->save('storage/' . $path . '.thumb.jpg');

        return [
            "success"   => true,
            "msg"       => "上传成功",
            "file_path" => [asset('storage/' . $path)]
        ];
    }

    public function attachment(Request $request)
    {
        $file = $request->attachment;
        $from = $request->from;
        $ext  = $file->getClientOriginalExtension();

        // 检查文件是否有效
        if (!$file->isValid()) {
            return [
                "success" => false,
                "msg"     => "无效的文件",
            ];
        }

        // 校验格式
        if (!in_array($ext, ['ppt', 'pptx', 'mp3', 'mp4'])) {
            return [
                "success" => false,
                "msg"     => "格式不正确（ppt、pptx、mp3、mp4）",
            ];
        }

        if ($ext == 'mp3') {
            $path = $file->storeAs($from, $file->hashName() . '.mp3', 'public');
        } else {
            $path = $file->store($from, 'public');
        }

        return [
            "success"       => true,
            "msg"           => "上传成功",
            'original_name' => $file->getClientOriginalName(),
            'size'          => $file->getClientSize(),
            'extension'     => $ext,
            "file_path"     => asset('storage/' . $path),
        ];
    }
}
